package com.hunan.yllxy.util;


import com.google.gson.Gson;
import com.hunan.yllxy.exceptions.CustomerException;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.swing.plaf.synth.Region;
import java.util.UUID;

/**
 * @Author: 刘华
 * @Date: 2025/7/1 下午6:06
 * @Version 1.0
 */

@Data
@AllArgsConstructor
@Slf4j
public class QiniuUtil {

    private final String accessKey = "Zv-3F8fo_pFTMVXPdhG5Jna7O3L9bsDd7iV1_bS0";
    private final String secretKey = "wNuNmMfjHcAK00hvV_ZAM5Vxoa3cvk1_wt_k3_cS";
    private final String bucket = "yllxy1";
    private final String url = "http://syptrms0o.hn-bkt.clouddn.com/";


    /*
     * 文件上传
     *
     * */
    public String upload(MultipartFile file) {
        Configuration cfg = new Configuration(Zone.huanan());
//        cfg.
//        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        UploadManager uploadManager = new UploadManager(cfg);

        Auth auth = Auth.create(accessKey, secretKey);

        String upToken = auth.uploadToken(bucket);
        String key = null;
        try {
            String originalFilename = file.getOriginalFilename();
            int i = originalFilename.lastIndexOf(".");
            String suffix = originalFilename.substring(i + 1);
            key = UUID.randomUUID() + "." + suffix;
            com.qiniu.http.Response put = uploadManager.put(file.getBytes(), key, upToken);
            //解析上传成功的结果
            int statusCode = put.statusCode;
            if (statusCode!=200){
                throw new CustomerException("上传失败");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("上传失败:{}", ex.getMessage());
        }
        return url + key;

    }

}
